const router = require("koa-router")();
const { handleRegister, handleLogin } = require("../controller/UserController");
const loginCheck = require("../middlewares/logincheck");

router.prefix("/users");

//注册功能
router.post("/register", async (ctx, next) => {
  let returnStr = {};
  const userInfo = ctx.request.body;
  //操作control 导入数据库
  try {
    const newUser = await handleRegister(userInfo);
    if (newUser) {
      returnStr = {
        errno: 0,
        data: newUser,
      };
    }
  } catch (error) {
    console.error("注册失败", error);
    returnStr = {
      errno: -1,
      message: "register failed",
    };
  } finally {
    ctx.body = returnStr;
  }
});

//登录功能
router.post("/login", async (ctx, next) => {
  const loginIfo = ctx.request.body;
  //调用loginController
  let returnData = {};
  try {
    const newLogin = await handleLogin(loginIfo);
    if (newLogin) {
      //登录成功了设置session
      ctx.session.userInfo = newLogin;
      returnData = {
        errno: 0,
        message: "登录成功",
        data: newLogin.username,
      };
    }
    //登录成功了需要返回session cookie
  } catch (error) {
    console.log(error);
    returnData = {
      errno: -1,
      message: "登录失败",
    };
    next();
  } finally {
    ctx.body = returnData;
  }
});

//获取登录信息
router.get("/getUserInfo", loginCheck, async (ctx, next) => {
  if (ctx.session.userInfo) {
    ctx.body = {
      errno: 0,
      data: ctx.session.userInfo,
    };
  }
});

module.exports = router;
